/**
 *	UTILITIES.C - implementation of UTILITIES.H
 *	Author: Fabio Garcia <fabio@blastpress.com>
 **/

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>

#include "utilities.h"

/** ErrorQuit() -- prints error and quits **/
void ErrorQuit(const char *msg) {
	fprintf(stderr, "UPNET: %s\n", msg);
	exit(EXIT_FAILURE);
}

/** ReadLine() -- reads a line from a socket connection **/
ssize_t ReadLine(int socket, void *vptr, size_t maxlen) {
	ssize_t n, rc;
	char c, *buffer;
	buffer = vptr;
	for(n = 1; n < maxlen; n++) {
		if((rc = read(socket, &c, 1)) == 1) {
			*buffer++ = c;
			if(c == '\n') break;
		} else if(rc == 0) {
			if(n == 1) return 0;
			else break;
		} else {
			if(errno == EINTR) continue;
			return -1;
		}
	}
	*buffer = 0;
	return n;
}

/** WriteLine() -- write a line to a socket connection **/
ssize_t WriteLine(int socket, const void *vptr, size_t n) {
	size_t nleft;
	ssize_t nwritten;
	const char *buffer;
	buffer = vptr;
	nleft = n;
	while(nleft > 0) {
		if((nwritten = write(socket, buffer, nleft)) < 0) {
			if(errno == EINTR) nwritten = 0;
			else return -1;
		}
		nleft -= nwritten;
		buffer += nwritten;
	}
	return n;
}
